import os , logging, time, shutil, sys, datetime, platform
import shutil
from colorama import Fore, Style, init
from logging.handlers import TimedRotatingFileHandler

init()

def clear_console():
    if os.name == 'nt':
        import subprocess
        subprocess.check_call('cls', shell=True, stdout=subprocess.DEVNULL)
    else:
        os.system('clear')

def setup_logging():
    logs_dir = 'logs'
    if not os.path.exists(logs_dir):
        os.makedirs(logs_dir)
    log_level = logging.INFO
    logging_format = "%(levelname)s - %(message)s"
    file_handler = TimedRotatingFileHandler(filename=os.path.join(logs_dir, f'de4py-logs-{datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")}.log'))
    file_formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
    file_handler.setFormatter(file_formatter)
    file_logger = logging.getLogger('file_logger')
    file_logger.setLevel(logging.INFO)
    file_logger.addHandler(file_handler)
    file_logger.info(f"System Architecture: {platform.architecture()[0]}, OS: {platform.platform()}, Python Version: {platform.python_version()}")
    logging.basicConfig(
        level=log_level,
        format=logging_format,
        handlers=[ColorizingStreamHandler(), file_handler])

class ColorizingStreamHandler(logging.StreamHandler):
    def emit(self, record):
        message = self.format(record)
        if record.levelno == logging.INFO:
            colored_message = f"{Fore.LIGHTBLUE_EX}{message}{Style.RESET_ALL}"
        elif record.levelno == logging.WARNING:
            colored_message = f"{Fore.YELLOW}{message}{Style.RESET_ALL}"
        elif record.levelno == logging.ERROR or record.levelno == logging.CRITICAL:
            colored_message = f"{Fore.RED}{message}{Style.RESET_ALL}"
        else:
            colored_message = message
        print(colored_message)


def draw_line():
    terminal_width = shutil.get_terminal_size().columns
    line = Fore.CYAN + "-" * terminal_width + Style.RESET_ALL
    print(line)

def align(text: str) -> str:
    """
    credits : https://github.com/SirDank/dankware/blob/main/dankware/__init__.py
    """
    width = shutil.get_terminal_size().columns
    aligned = text
    for _ in tuple(vars(Fore).values()) + tuple(vars(Style).values()):
        aligned = aligned.replace(_, '')

    text = text.splitlines()
    aligned = aligned.splitlines()
    for _ in range(len(aligned)):
        aligned[_] = aligned[_].center(width).replace(aligned[_], text[_])
    return str('\n'.join(aligned) + Style.RESET_ALL)

def water(text):
    os.system(""); faded = ""
    green = 10
    for line in text.splitlines():
        faded += (f"\033[38;2;0;{green};255m{line}\033[0m\n")
        if not green == 255:
            green += 15
            if green > 255:
                green = 255
    return faded
